package com.start.avue.tools;

import cn.hutool.core.util.ReUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.Collection;
import java.util.regex.Pattern;

@Slf4j
public class AvueTools {
    private static final Pattern URL_START = Pattern.compile("^http[s]{0,1}://", Pattern.CASE_INSENSITIVE);
    private static final Pattern URL_PATH_SEPARATOR = Pattern.compile("/+", Pattern.CASE_INSENSITIVE);

    public static String analysisUrl(String startHomeUrl, String url) {
        if (StringUtils.isAllBlank(url)) return url;
        if (URL_START.matcher(url).find()) {
            return url;
        }
        if (startHomeUrl.endsWith("/")) {
            startHomeUrl = startHomeUrl.substring(0, startHomeUrl.length() - 1);
        }
        if (url.startsWith("#{baseUrl}")) {
            url = url.replace("#{baseUrl}", "");
        }
        if (url.startsWith("/")) {
            url = url.substring(1);
        }
        url = ReUtil.replaceAll(url, URL_PATH_SEPARATOR, "/");
        if (url.startsWith("/")) {
            url = url.substring(1);
        }
        return startHomeUrl + "/" + url;
    }

    public static boolean strIsJson(String str) {
        boolean result = false;
        if (!StringUtils.isNotBlank(str)) {
            return false;
        }
        str = str.trim();
        if (str.startsWith("{") && str.endsWith("}")) {
            result = true;
        } else if (str.startsWith("[") && str.endsWith("]")) {
            result = true;
        }
        return result;
    }

    public static boolean objIsJson(Object obj) {
        if (obj == null) {
            return false;
        }
        if (obj instanceof JSON) {
            return true;
        }
        if (obj instanceof String && strIsJson((String) obj)) {
            return true;
        }
        try {
            JSONObject.toJSONString(obj);
            return true;
        } catch (Exception e) {
            log.error("obj 无法转换问json", e);
            return false;
        }
    }

    public static JSONArray objectToJSONArray(Object value) {
        JSONArray jsonArray = null;
        if (!objIsJson(value)) {
            return null;
        }
        if (value instanceof JSONArray) {
            jsonArray = (JSONArray) value;
        } else if (value instanceof Collection) {
            jsonArray = JSONArray.from(value);
        } else if (value.getClass().isArray()) {
            jsonArray = JSONArray.from(value);
        } else if (value instanceof String) {
            try {
                jsonArray = JSONArray.parseArray((String) value);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return jsonArray;
    }
}
